<template>
    <div id="move">
        <el-dialog
                :showClose="false"
                title="文件移动到"
                :visible.sync="moveVisibleFun"
                @closed="$emit('moveVisibleBox', false)"
                width="40%">
            <div>
                <div v-show="isAlive">
                    <!--<el-input placeholder="输入关键字进行过滤" class="filter-box" v-model="filterText" clearable></el-input>-->
                    <el-tree  v-show="isAlive" :data="dataFile"  highlight-current
                             node-key="id"
                            :check-strictly="true"
                            :default-expanded-keys="idTemp"
                            @node-click="handleNodeClick"
                            @node-expand="handleNodeExpand"
                            ref="tree2"
                            :render-content="renderContent">
                    </el-tree>
                </div>
                <el-form @submit.native.prevent v-if="newFileVisible"
                         :rules="rules"
                         :model="fileValidateForm"
                         ref="addForm" label-width="100px" class="demo-ruleForm" status-icon>
                    <el-form-item
                            label="新建文件夹"
                            prop="newfile">
                        <el-input type="age"  v-model="fileValidateForm.newfile" clearable></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="addFolder('addForm')">新  建</el-button>
                        <el-button @click="resetForm('addForm')">返  回</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer" v-if="isAlive">
                <el-button @click="$emit('moveVisibleBox', false) ">取 消</el-button>
                <el-button type="primary" @click="getCheckedKeys()">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%">
            <span>文件夹 <em style="color: #01b1a2">{{msg}}</em> 中已存在该文件，请选择其他文件夹转存</span>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        props: ['movePara', 'moveVisibleFun','nodeData'],
        data() {
            let checkFile = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('文件夹名字不能为空'));
                }else {
                    let reg = new RegExp('^[^\\\\\\/:.*?\\"<>| ]+$')
                    if (!reg.test(value)) {
                        callback(new Error('命名格式不正确 (文件名不能包含空格及 【/.:*?\\"<>|】)'));
                    }else if(value.length>20){
                        callback(new Error('文件夹名长度超出上限'));
                    }else{
                        callback();
                    }
                }
            };
            return {
                msg: '',
                dialogVisible: false,
                fileValidateForm: {
                    newfile: ''
                },
                rules: {
                    newfile: [
                        { validator: checkFile, trigger: 'blur' }
                    ],
                },
                filterText: '',
                dataFile: [{
                    id: localStorage.getItem('dirId'),
                    dirId: localStorage.getItem('dirId'),
                    label: '我的文档',
                    children: []
                }],
                idTemp: [localStorage.getItem('dirId')],
                removeNodeTemp: null,
                newFileVisible: false,
                isAlive: true,
                folderTemp: '',
                addFloderKey: '',
                currentChooseId:null,
            }
        },
        created() {
            this.initFiles()
        },
        watch: {
            filterText(val) {
                console.log(111111, val);
                this.$refs.tree2.filter(val);
            }
        },
        methods: {
            closed(){
                $emit('moveVisibleBox', false)
            },
            getCheckedKeys() {
                this.submitMove();
            },
            resetForm(formName) {
                this.folderTemp = ''
                this.isAlive = true
                this.newFileVisible = false
                this.$refs[formName].resetFields();
            },
            addFolder(formName) {
              console.log('folderTemp: ',    this.folderTemp);
              console.log('this.nodeTemp: ',    this.nodeTemp);
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let para = {
                            dirId: this.folderTemp.id,
                            fileType: 1,
                            fileName: this.fileValidateForm.newfile
                        }
                        this.$http.post("/file/mkdir", para).then(res => {
                            console.log("addFile", res);
                            if (res.status == 200) {
                              this.addFloderKey = res.data
                              console.log(222222,this.addFloderKey);
                              
                                console.log('this.idTemp', this.idTemp);
                              this.handleNodeClick(this.folderTemp, this.nodeTemp)
                              this.isAlive = true
                              this.newFileVisible = false
                                this.$message({
                                    type: "success",
                                    message: "新建成功"
                                });
                            }
                        });
                    }
                })
            },
            submitMove() {
                console.log(222222, this.movePara);
                console.log('==keys==', this.currentChooseId);
                let _this=this;
                let idArray=[];
                this.movePara.forEach(val=>{
                    if(val.id!=this.currentChooseId&&val.dirId!=this.currentChooseId){
                        idArray.push(val.id);
                    }
                });
                let para = {
                    operationIds:idArray, //移动文件和文件夹的id；
                    dirId: this.currentChooseId, //转存文件夹ID；
                }
                if (this.currentChooseId == null) {
                    this.$message({
                        message: '请选择文件夹或者新建文件夹',
                        type: "info"
                    });
                } else {
                    console.log('==para===',para);
                    this.$http.post('/file/mv', para).then(res=>{
                        console.log('/file/mv', res);
                        let {status, msg, data} = res
                         if (status === 200) {
                             this.$emit("clearSelsForDel", _this.nodeData);
                            this.$message.success('文件移动成功！')
                            this.$emit('moveVisibleBox', false)
                        }else if(status===500){
                            this.$emit("clearSelsForDel", _this.nodeData);
                            this.$message.warning(data);
                            this.$emit('moveVisibleBox', false)
                        }else{
                            this.$message.error('网络异常！');
                            this.$emit('moveVisibleBox', false)
                        }
                    })
                }
            },
          appendNode(data, node) {
                console.log('appendNode:',data);
                this.folderTemp = data
                this.nodeTemp = node
                this.newFileVisible = true
                this.isAlive = false
            },
            remove(node, data) {
                const parent = node.parent;
                const children = parent.data.children || parent.data;
                const index = children.findIndex(d => d.id === data.id);
                children.splice(index, 1);
            },
            renderContent(h, { node, data, store }) {
                return (
                    <span class="custom-tree-node">
                    <span>{node.label}</span>
                <span>
                <el-button size="mini" type="text" icon="fa fa-plus" style="margin-left:10px;" on-click={ () => this.appendNode(data, node) }></el-button>
                </span>
                </span>);
            },
            initFiles() {
                this.$http.get('/file/ls').then(res => {
                    let {data} = res
                    console.log('initFiles', res.data)
                    this.dataFile[0].children = []
                    if (res.status === 200 && data !== null) {
                        data.forEach((v, k) => {
                            if (v.fileType === 1) {
                                this.dataFile[0].children.push({
                                    id: v.id,
                                    dirId: v.dirId,
                                    label: v.fileName,
                                    type: v.fileType,
                                    children: [{}]
                                })
                            }
                        })
                      this.idTemp = [localStorage.getItem('dirId'), this.idTemp]
                    }
                }, err => {
                    this.$message({
                        message: '网络出错!!',
                        type: 'error'
                    })
                    console.log(err)
                })
            },
            handleNodeExpand(data, node, comp) {
                this.removeNodeTemp = node
                console.log('Expand', data, node);
                if (data.label !== '我的文档') {
                    this.handleGetChildNode(data.id)
                } else {
                    this.initFiles()
                }
            },
            handleNodeClick(data, node) {
                this.removeNodeTemp = node
                console.log(data.label);
                //点击我的文档
                if (data.label == '我的文档') {
                    this.initFiles()
                } else {
                  console.log('handleNodeClick=', node.childNodes);
                  this.handleGetChildNode(data.id)
                }
                this.currentChooseId=data.id

            },
            async handleGetChildNode(id) {
              let nodeBox = await this.$http.post('/file/clickdir', {id: id}).then(res => {
                    let {data} = res
                    console.log('获取子节点', res);
                    if (data !== null) {
                        let tempInfo = []
                        data.forEach(v => {
                            // 过滤掉文件数据，并且重新组织数据
                            if (v.fileType === 1) {
                                tempInfo.push({
                                    id: v.id,
                                    dirId: v.dirId,
                                    label: v.fileName,
                                    type: v.fileType,
                                    children: [{}]
                                })
                            }
                        })
                        console.log('tempInfo', tempInfo);
                        // 文件夹不为空
                        if (!(tempInfo == false)) {
                            //递归查找添加子节点
                            !(function getCurrentPart(id, items) {
                                let result;
                                for (let i in items) {
                                    let item = items[i];
                                    if (item.id === id) {
                                        result = item;
                                        result.children = tempInfo
                                        console.log('tempInfo===', tempInfo);
                                        break;
                                    } else if (item.children) {
                                        result = getCurrentPart(id, item.children);
                                    }
                                }
                                console.log('result', result);
                                return result;
                            })(tempInfo[0].dirId, this.dataFile)
                            console.log('dataFile',this.dataFile);
                        }else {
                            //删除空节点
                            console.log('删除空节点', this.removeNodeTemp);
                            if (this.removeNodeTemp !== null) {
                                this.remove(this.removeNodeTemp.childNodes[0], this.removeNodeTemp.childNodes[0].data)
                            }
                        }
                    }else {
                        //删除空节点
                        console.log('删除空节点', this.removeNodeTemp);
                        if (this.removeNodeTemp !== null) {
                            this.remove(this.removeNodeTemp.childNodes[0], this.removeNodeTemp.childNodes[0].data)
                        }
                    }
                    console.log('dataFile》》》》',this.dataFile);
                    return this.dataFile
                }, err => {
                    this.$message({
                        message: '网络出错!!',
                        type: 'error'
                    })
                })
              console.log('nodeBox:::',nodeBox);
              if (nodeBox !== undefined) {
                if (!(!this.addFloderKey && this.addFloderKey !== '')) {
                  let TheNode = this.removeNodeTemp.childNodes.find( element => {
                    console.log(this.addFloderKey, element.key);
                    return this.addFloderKey == element.key
                  })
                  TheNode.isCurrent = true
                  this.removeNodeTemp.expanded = true
                  console.log('TheNode==',TheNode, this.addFloderKey);
                }
              }
            },
            filterNode(value, data) {
                console.log(1,value, 2, data);
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            }
        },
    }
</script>

<style lang="scss">
    #move {
        .el-dialog__body {
            padding: 20px;
        }
        .filter-box {
            margin-bottom: 10px;
        }
    }
</style>

